//
//  CQExtralTagNormalCollectionView.m
//  CJUIKitDemo
//
//  Created by ciyouzen on 2017/9/11.
//  Copyright © 2017年 dvlproad. All rights reserved.
//

#import "CQExtralTagNormalCollectionView.h"

#import "CQTagLookCollectionViewCell.h"
#import "CQTagAddCollectionViewCell.h"

#import "CJDataSourceSettingModel.h"

@interface CQExtralTagNormalCollectionView () <UICollectionViewDelegateFlowLayout, UICollectionViewDelegate> {
    
}
@property (nonatomic, copy, readonly) NSString *(^textFormatBlock)(NSString *originText); /**< 将text格式化的方法（比如传入省市，但我们只想显示市），默认nil，表示使用原值显示 */
@property (nonatomic, copy, readonly) void(^addTagBlock)(NSIndexPath *indexPath);       /**< 添加tag的方法 */
@property (nonatomic, copy, readonly) void(^updateTagBlock)(NSIndexPath *indexPath, NSString *oldTagString);   /**< 更新tag的方法 */

@property (nonatomic, copy, readonly) void(^ _Nullable tagChangeBlock)(NSMutableArray<CJTagSectionDataModel *> *tagSectionModels, NSIndexPath *indexPath);

@end


@implementation CQExtralTagNormalCollectionView

/*
 *  初始化标签视图
 *
 *  @param itemHorizontalSpacing    两个item之间的水平间距
 *  @param itemVerticalSpacing      两个item之间的竖直间距
 *  @param sectionLeftRightInset    每个section左右离边缘的间距
 *  @param sectionSpacing           两个section之间的间距
 *  @param sectionSettingBlock      根据需要设置每个section。（当某个section的这个block①为nil时,该区个数无限制且无额外item,即显示实际个数；②为非nil时,该区个数可限制且可设置个数未超限时,额外item的位置(当有个数限制且超过后，+号会隐藏)）
 *  @param textFormatBlock          将text格式化的方法（比如传入省市，但我们只想显示市），默认nil，表示使用原值显示
 *  @param addTagBlock              添加tag的方法
 *  @param updateTagBlock           更新所添加的tag的文本方法
 *
 *  @return 标签视图
 */
- (instancetype)initWithItemHorizontalSpacing:(CGFloat)itemHorizontalSpacing
                          itemVerticalSpacing:(CGFloat)itemVerticalSpacing
                        sectionLeftRightInset:(CGFloat)sectionLeftRightInset
                               sectionSpacing:(CGFloat)sectionSpacing
                          sectionSettingBlock:(CJDataSourceSettingModel* (^ _Nullable)(NSInteger section))sectionSettingBlock
                              textFormatBlock:(NSString *(^ _Nullable)(NSString *originText))textFormatBlock
                                  addTagBlock:(void(^)(NSIndexPath *indexPath))addTagBlock
                               updateTagBlock:(void(^)(NSIndexPath *indexPath, NSString *oldTagString))updateTagBlock
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = itemHorizontalSpacing;
    layout.minimumLineSpacing = itemVerticalSpacing;
    layout.sectionInset = UIEdgeInsetsMake(0, sectionLeftRightInset, sectionSpacing, sectionLeftRightInset);
    self = [super initWithFrame:CGRectZero collectionViewLayout:layout];
    if (self) {
        _textFormatBlock = textFormatBlock;
        _addTagBlock = addTagBlock;
        _updateTagBlock = updateTagBlock;
        
        [self setupConfigureWithSectionSettingBlock:sectionSettingBlock];
        
    }
    return self;
}


- (void)setupConfigureWithSectionSettingBlock:(CJDataSourceSettingModel* (^ _Nullable)(NSInteger section))sectionSettingBlock {
    self.backgroundColor = [UIColor clearColor];
    self.allowsMultipleSelection = YES; // 开启多选，修复点击自定义cell的时候，之前的cell被取消选中的情况
    
    
    
    
    //以下值，可选设置
    //self.allowsMultipleSelection = YES; //是否打开多选
    
    /* 设置Register的Cell或Nib */
    [self registerClass:[CQTagLookCollectionViewCell class] forCellWithReuseIdentifier:@"normalCell"];
    [self registerClass:[CQTagAddCollectionViewCell class] forCellWithReuseIdentifier:@"addCell"];
    
    /* 创建DataSource */
    CJExtralItemCollectionViewDataSource *mDataSource = [[CJExtralItemCollectionViewDataSource alloc] initWithSectionSettingBlock:sectionSettingBlock cellForItemAtIndexPathBlock:^UICollectionViewCell *(UICollectionView *collectionView, NSIndexPath *indexPath, BOOL isExtralItem) {
        if (!isExtralItem) {
            CQTagModel *tagModel = [self.mDataSource dataModelAtIndexPath:indexPath];
            CQTagLookCollectionViewCell *dataCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"normalCell" forIndexPath:indexPath];
            dataCell.shouldNormalAndSelectedSame = YES;
            
            NSString *cellText = tagModel.name;
            if (self.textFormatBlock) {
                cellText = self.textFormatBlock(tagModel.name);
            }
            dataCell.text = cellText;
            
            return dataCell;
            
        } else {
            CQTagAddCollectionViewCell *extralCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"addCell" forIndexPath:indexPath];
            extralCell.textLabel.text = @"";
            return extralCell;
        }
    }];
    self.mDataSource = mDataSource;
    
    
    
    /* 设置DataSource和Delegate */
    self.dataSource = self.mDataSource;
    self.delegate = self;
}


/*
 *  设置回调
 *
 *  @param tagCountChangeBlock  tag个数内容改变的回调
 */
- (void)setupTagCountChangeBlock:(void(^ _Nullable)(NSMutableArray<CJTagSectionDataModel *> *tagSectionModels, NSIndexPath *indexPath))tagCountChangeBlock {
    _tagChangeBlock = tagCountChangeBlock;
}

#pragma mark - Event
/// 添加标签及其内容
- (void)addTagString:(NSString *)tagString indexPath:(NSIndexPath *)indexPath {
    [self addTagString:tagString detailTagName:nil indexPath:indexPath];
}

/// 添加标签及其内容
- (void)addTagString:(NSString *)tagString detailTagName:(nullable NSString *)detailName indexPath:(NSIndexPath *)indexPath {
    CJTagSectionDataModel *sectionModel = self.mDataSource.sectionModels[indexPath.section];
    NSMutableArray *dataModels = sectionModel.values;
    
    CJDataSourceSettingModel *settingModel = self.mDataSource.sectionSettingBlock(indexPath.section);
    NSInteger maxDataModelShowCount = settingModel.maxDataModelShowCount;
    if (dataModels.count >= maxDataModelShowCount) {
        NSAssert(NO, @"个数已满，无法再添加，如果你是要更新，请调用另一个方法updateTagString");
    }
    if (tagString.length == 0) {
        return;
    }
    CQTagModel *tagModel = [[CQTagModel alloc] init];
    tagModel.name = tagString;
//    tagModel.detailName = detailName;
    tagModel.editEnable = YES;
    
    [dataModels addObject:tagModel];
//    [self reloadItemsAtIndexPaths:@[indexPath]];
    [self reloadData];
    
    !self.tagChangeBlock ?: self.tagChangeBlock(self.mDataSource.sectionModels, indexPath);
}

/// 删除指定位置的标签及其内容
- (void)deleteIndexPath:(NSIndexPath *)indexPath {
    CJTagSectionDataModel *sectionModel = self.mDataSource.sectionModels[indexPath.section];
    NSMutableArray *dataModels = sectionModel.values;
    [dataModels removeObjectAtIndex:indexPath.item];
    [self reloadData];
    
    !self.tagChangeBlock ?: self.tagChangeBlock(self.mDataSource.sectionModels, indexPath);
}

/// 更新标签内容
- (void)updateTagString:(NSString *)tagString indexPath:(NSIndexPath *)indexPath {
    [self updateTagString:tagString detailTagName:nil indexPath:indexPath];
}

/// 更新标签内容
- (void)updateTagString:(NSString *)tagString detailTagName:(nullable NSString *)detailName indexPath:(NSIndexPath *)indexPath {
    if (tagString.length == 0) {
        return;
    }
    CQTagModel *tagModel = [self.mDataSource dataModelAtIndexPath:indexPath];
    tagModel.name = tagString;
//    tagModel.detailName = detailName;

    [self reloadItemsAtIndexPaths:@[indexPath]];
    [self selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    
    !self.tagChangeBlock ?: self.tagChangeBlock(self.mDataSource.sectionModels, indexPath);
}


#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat cellHeight = 34;
    
    CGFloat cellWidth = 0;
    
    BOOL isExtralItem = [self.mDataSource isExtraItemIndexPath:indexPath];
    if (isExtralItem) {
        cellWidth = 100;
    } else {
        //CQTagModel *tagModel = [self.mDataSource dataModelAtIndexPath:indexPath];
        cellWidth = 100;
    }
    
    return CGSizeMake(cellWidth, cellHeight);
}


#pragma mark - Reload
/// 只有一个section的时候使用
- (void)reloadWithTagModels:(NSMutableArray<CQTagModel *> *)tagModels {
    CJTagSectionDataModel *sectionModel = [[CJTagSectionDataModel alloc] init];
    sectionModel.values = tagModels;
    
    NSMutableArray *sectionModels = [NSMutableArray arrayWithArray:@[sectionModel]];
    [self reloadWithTagSectionModels:sectionModels];
}

/// 有多个section的时候使用
- (void)reloadWithTagSectionModels:(NSMutableArray<CJTagSectionDataModel *> *)sectionModels {
    self.mDataSource.sectionModels = sectionModels;
    [self reloadData];
}


#pragma mark - UICollectionViewDelegate
// 此点击部分请在子类中实现
////“点到”item时候执行的时间(allowsMultipleSelection为默认的NO的时候，只有选中，而为YES的时候有选中和取消选中两种操作)
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    BOOL isExtralItem = [self.mDataSource isExtraItemIndexPath:indexPath];
    if (isExtralItem) {
        if (self.addTagBlock) {
            self.addTagBlock(indexPath);
        }
    } else {
        if (self.updateTagBlock) {
            CQTagModel *tagModel = [self.mDataSource dataModelAtIndexPath:indexPath];
            self.updateTagBlock(indexPath, tagModel.name);
        }
    }
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    if ([cell isKindOfClass:[CQTagLookCollectionViewCell class]])
    {
        return YES;
    }
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    BOOL isExtralItem = [self.mDataSource isExtraItemIndexPath:indexPath];
    if (isExtralItem) {
        if (self.addTagBlock) {
            self.addTagBlock(indexPath);
        }
    }
}

@end
